package com.bw.attendance.sign

import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.bw.attendance.sign.entity.SignEntity
import com.bw.attendance.sign.entity.SignResponseEntity
import com.bw.attendance.sign.entity.SignState
import com.bw.common.mvi.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.util.HashMap

class SignViewModel : BaseViewModel<SignRepo,SignState>() {

    private var page = 1

    override fun createRepo(): SignRepo {
        return SignRepo()
    }

    override fun createState(): SignState {
        return SignState(false,SignResponseEntity(),false,ArrayList())
    }

    //请求获取历史记录
    fun requestSignHistory(userId : Int){
        val map = HashMap<String,Any>()
        map["userId"] = userId
        map["page"] = page
        viewModelScope.launch{
            repo.requestSignHistory(map).flowOn(Dispatchers.IO)
                .catch { t : Throwable->
                    LogUtils.e("errorMsg:${t.message}") }
                .onStart { mutableContainer.updateRequestState { copy(request=true) } }
                .onCompletion { mutableContainer.updateRequestState { copy(complate=true) }  }
                .collect{
                    val signEntity = it as SignEntity
                    mutableContainer.updateUiState { copy(dataState=true, data = signEntity.data) }
                }
        }
    }

    fun requestSign(userId : Int,signLat:Double,signLong:Double){
        val map = HashMap<String,Any>()
        map["userId"] = userId
        map["SignLat"] = signLat
        map["SignLong"] = signLong
        viewModelScope.launch{
            repo.requestSign(map).flowOn(Dispatchers.IO)
                .catch {  t : Throwable->
                    LogUtils.e("errorMsg:${t.message}")  }
                .onStart { mutableContainer.updateRequestState { copy(request=true,complate = false) } }
                .onCompletion { mutableContainer.updateRequestState { copy(complate=true,request = false) }  }
                .collect{
                    val signResponseEntity = it as SignResponseEntity
                    mutableContainer.updateUiState { copy(signState=true,
                        sign = signResponseEntity,dataState = false) }
                }
        }

    }

}